package com.banciyuan.bcywebview.biz.search;

import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.biz.pc.zone.smooth.SmoothPersonActivity;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.daoexample.model.SearchContent;

/**
 * Created by squall on 2015/9/7.
 */
public class SearchPersonFragment extends SearchBaseFragment {

    private PullToRefreshListView mRefreshLv;
    private ListView mContentLv;
    private LinearLayout ll_nodata;
    private View result_nums;
    private LayoutInflater inflater;
    private TextView result_num_tv;
    private List<SearchContent> slist = new ArrayList<>();
    private SearchComplexAdapter mAdapter;
    private String count;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        this.inflater = inflater;
        View viewroot = inflater.inflate(R.layout.search_complex_fragment, null);
        initArgs();
        initProgressbar(viewroot);
        initUi(viewroot);
        initAction();
        return viewroot;
    }

    @Override
    protected void initArgs() {
        query = getArguments().getString("query");
    }

    @Override
    public void fetchData() {
        initData();
    }

    @Override
    protected void initAction() {
        mRefreshLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                loading = false;
                end_flag = false;
                page = 1;
                initData();
            }
        });

        mRefreshLv.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!end_flag && !loading) {
                    page++;
                    initData();
                }
            }
        });

        mContentLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                int postion = i - 2;
                if (postion < 0 || postion >= slist.size()) {
                    return;
                }
                if (slist.get(postion).getOtype().equals("user") && slist.get(postion).getOtype_data().equals("user")) {
                    gotoUtil.gotoAct(getActivity(), SmoothPersonActivity.class, slist.get(postion).getUid());
                }
            }
        });
    }

    @Override
    protected void initUi(View rootview) {
        mRefreshLv = (PullToRefreshListView) rootview.findViewById(R.id.search_refresh_lv);
        mContentLv = mRefreshLv.getRefreshableView();
        ll_nodata = (LinearLayout) rootview.findViewById(R.id.discover_search_nodata_layout);

        result_nums = inflater.inflate(R.layout.search_result_num, null);
        result_num_tv = (TextView) result_nums.findViewById(R.id.ground_zan_type_tv);

        mContentLv.addHeaderView(result_nums);

    }

    @Override
    protected void initData() {
        loading = true;
        SearchHelper searchHelper = new SearchHelper(getActivity(), new ISearchhelper() {
            @Override
            public void succ(String type, String succ) {
                try {
                    JSONObject jsonObject = new JSONObject(succ);
                    JSONObject jsonObject1 = jsonObject.getJSONObject(HttpUtils.UPLOAD_DATA);
                    count = jsonObject1.getString("total");
                    result_num_tv.setText(Html.fromHtml(String.format(getString(R.string.releated_user_pink), count)));
                    JSONArray jsonArray = jsonObject1.getJSONArray("results");
                    Gson gson = new Gson();
                    List<SearchContent> templist = gson.fromJson(jsonArray.toString(), new TypeToken<List<SearchContent>>() {
                    }.getType());
                    if (!templist.isEmpty()) {
                        dealResult(SearchHelper.popIllegal(templist, TimelineFactory.TIMELINE_TYPE_OTHER));
                    } else {
                        if (page == 1) {
                            ll_nodata.setVisibility(View.VISIBLE);
                        }
                        mRefreshLv.onRefreshComplete();
                        mProgressbarHelper.onSuccess();
                        loading = false;
                        end_flag = true;
                    }

                } catch (Exception e) {
                    if (null != mRefreshLv && null != mProgressbarHelper) {
                        mRefreshLv.onRefreshComplete();
                        mProgressbarHelper.onFailed();
                    }
                    loading = false;
                }
            }

            @Override
            public void fail(String type) {
                mProgressbarHelper.onFailed();
            }
        });
        searchHelper.getSearch("user", page, query);
    }

    private void dealResult(List<SearchContent> tempList) {
        ll_nodata.setVisibility(View.GONE);
        if (page == 1) {
            slist.clear();
        }
        slist.addAll(tempList);
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        } else {
            mAdapter = new SearchComplexAdapter(slist, getActivity());
            mRefreshLv.setAdapter(mAdapter);
        }
        mRefreshLv.onRefreshComplete();
        mProgressbarHelper.onSuccess();
        loading = false;
    }
}
